import React, { useState, useEffect, useRef } from 'react';
import SearchList from '@/components/SearchList';
import { Table, Button, notification, Tooltip, Upload, Modal } from 'antd';
import { transFormIndex, showDeleteConfirm } from '@/utils/util';
import {
  EyeFilled,
  EditFilled,
  DeleteFilled,
  PlusCircleFilled,
  ExportOutlined,
  ImportOutlined,
  FileExcelOutlined,
} from '@ant-design/icons';
import API, { downloadFn } from '@/api/xjindex.js';
import { useModel } from 'umi';

// 信息资产
const PropertyManage = ({
  isSelected,
  selectedKey,
  createLink,
  editLink,
  checkLink,
}) => {
  const { initialState } = useModel('@@initialState');
  const [WLLX, setWLLX] = useState([]);
  const [YWLX, setYWLX] = useState([]);
  const { userId, orgId } = initialState.info;
  const [dataSource, setDataSource] = useState([]);
  const [params, setParams] = useState({
    pageNo: 1,
    pageSize: 10,
    systemName: '',
    affiliatedUnit: -1,
    orgId,
    dbcpdj: -1,
    businessType: -1,
    networkType: -1,
    sfdbdjba: -1,
  });
  const [pagination, setPagination] = useState({
    total: 0, //总数
    pageSize: 10, //每页条数
    current: 1,
    showQuickJumper: true,
  });
  const searchList = [
    {
      name: 'systemName',
      key: 'systemName;',
      title: '系统名称',
      type: 'input',
    },
    {
      name: 'businessType',
      key: 'businessType',
      title: '业务类型',
      type: 'select',
      otherProps: {
        options: YWLX,
      },
    },
    {
      name: 'networkType',
      key: 'networkType',
      title: '网络类型',
      type: 'select',
      otherProps: {
        options: WLLX,
      },
    },
    {
      name: 'sfdbdjba',
      key: 'sfdbdjba',
      title: '是否等保定级备案',
      type: 'select',
      otherProps: {
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
      },
    },
    {
      name: 'dbcpdj',
      key: 'dbcpdj',
      title: '等保测试等级',
      type: 'select',
      otherProps: {
        options: [
          {
            label: '1级',
            value: 1,
          },
          {
            label: '2级',
            value: 2,
          },
          {
            label: '3级',
            value: 3,
          },
        ],
      },
    },
  ];
  if (isSelected) {
    params.affiliatedUnit = selectedKey;
  } else {
    params.affiliatedUnit = -1;
  }

  const pageSizeChange = (page) => {
    setParams({
      ...params,
      pageNo: page.current,
      pageSize: page.pageSize,
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      render: (text, r, index) => transFormIndex(pagination, index),
    },
    {
      title: '系统名称',
      dataIndex: 'systemName',
      align: 'center',
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      align: 'center',
      render: (text, r) => {
        const result = YWLX.map((item) => {
          if (item.value === r.businessType) {
            return item.label;
          }
        });
        return <>{result}</>;
      },
    },
    {
      title: '网络类型',
      dataIndex: 'networkType',
      align: 'center',
      render: (text, r) => {
        const result = WLLX.map((item) => {
          if (item.value === r.networkType) {
            return item.label;
          }
        });
        return <>{result}</>;
      },
    },
    {
      title: '访问地址',
      dataIndex: 'accessAddress',
      align: 'center',
    },
    {
      title: '是否等保定级备案',
      dataIndex: 'sfdbdjba',
      align: 'center',
      render: (text, r) => {
        return r.sfdbdjba === 0 ? '否' : '是';
      },
    },
    {
      title: '等保测评等级',
      dataIndex: 'dbcpdj',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'Operation',
      align: 'center',
      render: (text, record) => (
        <div>
          <Tooltip title="查看">
            <Button
              type="link"
              icon={<EyeFilled />}
              className="table-icon"
              onClick={checkLink.bind(null, record.id)}
            ></Button>
          </Tooltip>
          {record.createId == userId ? (
            <>
              <Tooltip title="编辑">
                <Button
                  type="link"
                  icon={<EditFilled />}
                  className="table-icon"
                  onClick={editLink.bind(null, record.id)}
                ></Button>
              </Tooltip>
              <Tooltip title="删除">
                <Button
                  type="link"
                  icon={<DeleteFilled />}
                  className="table-icon"
                  onClick={() => showDeleteConfirm(() => delFn(record.id))}
                ></Button>
              </Tooltip>
            </>
          ) : null}
        </div>
      ),
    },
  ];
  const delFn = (id) => {
    API.deleteInfo({ id: id }).then((res) => {
      if (res) {
        notification.success({
          message: '删除成功',
        });
        initList(params);
      }
    });
  };

  function changParams(data) {
    setParams({
      ...data,
    });
  }

  function initList(params = {}) {
    const dd = {
      pageNo: 1,
      pageSize: 10,
      systemName: '',
      affiliatedUnit: -1,
      orgId: orgId,
      dbcpdj: -1,
      businessType: -1,
      networkType: -1,
      sfdbdjba: -1,
    };
    for (let d in dd) {
      if (params[d] === undefined) {
        params[d] = dd[d];
      }
    }
    API.getAllAssetInfo(params).then((res) => {
      if (res) {
        const result = res.t.queryList.map((item) => {
          return {
            ...item,
            dbcpdj: item.dbcpdj ? item.dbcpdj + '级' : '',
          };
        });
        setDataSource(result);
        setPagination({
          ...pagination,
          total: res.t.totalSize, //总数
          current: res.t.currentPage,
          pageSize: res.t.pageSize,
        });
      }
    });
  }
  const props = {
    name: 'file',
    action: '/jiaotong/assetInfo/importExcel',
    headers: {
      jwt: localStorage.getItem('jwt'),
    },
    showUploadList: false,
    maxSize: 50,
    maxCount: 1,
    accept: ['.xlsx,.xls'],
    onChange: ({ file }) => {
      if (file.status === 'done') {
        console.log(111);
        if (file.response.code === '0001') {
          notification.success({ message: '文件上传成功', duration: 3 });
        } else if (file.response.code === '0000') {
          notification.error({
            message: `文件上传失败，失败原因：${file.response.desc}`,
          });
        }
      } else if (file.status === 'error') {
        notification.warning({ message: '文件上传失败，请重试' });
      }
      initList(params);
    },
  };
  const expotEXCEL = () => {
    downloadFn(params);
  };

  const childRefs = useRef(null);
  //编辑列表
  const edictRow = (text) => {
    //打开编辑弹窗 调用子组件身上的方法打开
    childRefs.current.searchFn();
  };

  useEffect(() => {
    API.getXXZCWLLX().then((res) => {
      if (res) {
        const result = res.t.map((item) => {
          return {
            label: item.dictItemName,
            value: item.dictItemType,
          };
        });
        setWLLX(result);
      }
    });
    API.getXXZCYWLX().then((res) => {
      if (res) {
        const result = res.t.map((item) => {
          return {
            label: item.dictItemName,
            value: item.dictItemType,
          };
        });
        setYWLX(result);
      }
    });
  }, []);

  useEffect(() => {
    if (isSelected) {
      console.log(childRefs.current.searchFn());
      initList({ ...params, ...childRefs.current.searchFn() });
      // initList(params);
    }
  }, [params, selectedKey]);
  return (
    <>
      <SearchList
        ref={childRefs}
        searchList={searchList}
        initList={changParams}
      ></SearchList>
      <div className="bgf main-x">
        <div className="tools-x">
          <Button
            type="link"
            icon={<PlusCircleFilled />}
            className="btn-icon"
            onClick={createLink}
          >
            新增
          </Button>
          <Button
            type="link"
            icon={<ExportOutlined />}
            className="btn-icon"
            disabled={dataSource.length === 0}
            onClick={() => expotEXCEL()}
          >
            导出
          </Button>
          <Button
            type="link"
            className="btn-icon"
            icon={<FileExcelOutlined />}
            href="/jiaotong/assetInfo/downloadTemplate"
            download
            target="_blank"
          >
            模板
          </Button>
          <Upload {...props}>
            <Button icon={<ImportOutlined />} className="btn-icon" type="link">
              导入
            </Button>
          </Upload>
        </div>
        <Table
          columns={columns}
          rowKey="id"
          dataSource={dataSource}
          pagination={pagination}
          className="custom-table"
          onChange={pageSizeChange}
        ></Table>
      </div>
    </>
  );
};

export default PropertyManage;
